import os
import sys

import pandas as pd
from cq_calc import cq_calculator
from utils import run_cmd, call_sourcemeter, call_fortify


def scan_whole_work(repo_path, commit_hash=''):
    """使用sourcemeter和fortify扫描repo_path

    :param repo_path:
    :param commit_hash:
    :return:
    """
    call_sourcemeter(repo_path, commit_hash)
    call_fortify(repo_path, commit_hash)


def find_authors_every_unit(df, repo_path):
    """根据sourcemeter扫描结果中的Path、Line、EndLine调用git blame命令，确定每个单位（class、method、file，取决于传入的df）的作者列表

    :param df: 类级代码质量表
    :param repo_path:
    :return: 返回包含作者列表的列表
    """
    auhtors_list = []
    for index, series in df.iterrows():
        # 拿到起止行对应的author
        file_path = series['Path']
        file_path = file_path.replace('\\', '/')
        # 从repo_path开始截取git仓库路径
        file_path = file_path[file_path.find(repo_path) + len(repo_path) + 1:]
        # start_line = series['Line']
        # end_line = series['EndLine']
        # ssh me@otherhost "cd repo && git blame"
        # cmd_line = f"git blame {file_path} -w  --line-porcelain | sed -n 's/^author //p' | sort | uniq"
        # 由于sort对于中文字符处理的问题，这里改成手动去重
        # 原先用wait()方法会出错，所以这里先做一步uniq，现在用communicate就可以不加uniq
        cmd_line = f"git blame {file_path} -w  --line-porcelain | sed -n 's/^author //p' | uniq"
        cmd_line = cmd_line.replace("'", '"')
        lines = run_cmd(
            # -w忽略空格，-L对起止行调用命令
            # f"git blame {file_path} -w -L {start_line},{end_line} --line-porcelain | sed -n 's/^author //p' | sort | uniq",
            # f"git blame {file_path} -w  --line-porcelain | sed -n 's/^author //p' | sort | uniq",
            cmd_line,
            path=repo_path
        )
        lines = sorted(lines)
        uniq_lines = []
        for line in lines:
            if line not in uniq_lines:
                uniq_lines.append(line)
        auhtors_list.append(uniq_lines)
    return auhtors_list


def calc_whole_work_with_person(repo_path, commit_hash=''):
    """
    计算每个类的代码质量指标，调用find_authors_every_unit方法加入authors字段，代表每个类的作者列表，
    将authors字段展开（同时重复其他字段）成author字段，方便后序聚合
    :param repo_path:
    :param commit_hash:
    :return:
    """
    if not commit_hash:
        commit_hash = run_cmd('git rev-parse HEAD', repo_path)[0]
    # 修改结果文件的地址！！！
    proj_short_name = repo_path.split('/')[-1]
    scan_results_dir = f'scan/{proj_short_name}/java/{commit_hash}'
    df = cq_calculator(scan_results_dir, proj_short_name)
    df['authors'] = find_authors_every_unit(df, repo_path)
    # 展开authors方便聚合
    l = []
    for index, series in df.iterrows():
        for author_name in series['authors']:
            d = series.copy()
            d['author'] = author_name
            l.append(d)
    df = pd.DataFrame(l)
    xlsx_filename = '_'.join(remote_path.split("/")) + "_" + commit_hash + ".xlsx"
    df.to_excel(xlsx_filename)
    # print(df)
    print(xlsx_filename)


if __name__ == '__main__':
    os.chdir("D:/code_and_results")
    args = sys.argv
    repo_path = args[1]
    remote_path = args[2]
    # repo_path = 'D:/projects/alibaba/easyexcel'
    # remote_path = 'alibaba/easyexcel'
    # checkout_personal_work(repo_path)
    # scan_personal_work(repo_path, author_name)
    # calc_personal_work(repo_path, author_name)
    scan_whole_work(repo_path)
    calc_whole_work_with_person(repo_path)
